package main

import (
	"fmt"
	"go_final/mxshop_api/userop_web/global"
	initialize "go_final/mxshop_api/userop_web/initialize"
	"go_final/mxshop_api/userop_web/utils"
	"go_final/mxshop_api/userop_web/utils/register/consul"
	validator2 "go_final/mxshop_api/userop_web/validator"
	"os"
	"os/signal"
	"syscall"

	ut "github.com/go-playground/universal-translator"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
)

func main() {
	// 1.初始化logger
	initialize.InitLogger()

	// 2.初始化配置
	initialize.InitConfig()

	// 初始化服务连接
	initialize.InitSrvConnWithLoadBalance()

	// 3.初始化翻译器
	err := initialize.InitTrans("zh")
	if err != nil {
		panic(err)
	}
	// 注册自定义校验器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("mobile", validator2.ValidateMobile)
		_ = v.RegisterTranslation("mobile", global.Trans, func(ut ut.Translator) error {
			return ut.Add("mobile", "{0}非法的手机号!", true) // see universal-translator for details
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mobile", fe.Field())
			return t
		})
	}

	debug := initialize.GetEnvInfo("MUSHOP_DEV")
	// 线上环境自动获取端口号
	if !debug {
		port, err := utils.GetFreePort()
		if err == nil {
			global.ServerConfig.Port = port
		}
	}

	// 4.初始化Router
	router := initialize.Routers()

	// 5.服务注册
	fmt.Println("global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port", global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	registerClient := consul.NewRegistry(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	serviceID := fmt.Sprintf("%s", uuid.NewV4())
	err = registerClient.Register("192.168.4.170", global.ServerConfig.Port, global.ServerConfig.Name,
		global.ServerConfig.Tags,
		serviceID)
	if err != nil {
		zap.S().Panic("服务注册失败", err.Error())
	}

	zap.S().Infof("启动服务成功, 端口: %d", global.ServerConfig.Port)

	go func() {
		err = router.Run(fmt.Sprintf(":%d", global.ServerConfig.Port))
		if err != nil {
			zap.S().Panic("启动失败: ", err)
		}
	}()

	// 接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	<-quit
	if err = registerClient.DeRegister(serviceID); err != nil {
		zap.S().Info("注销服务失败", err)
	} else {
		zap.S().Info("注销服务成功")
	}
}
